package com.nameless.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayUtil;
import com.nameless.entity.WeiXiEntity;
import com.nameless.service.WiXinRechargeService;
import com.nameless.utils.HttpClient;
import com.nameless.utils.UuidTradeNo;
import com.nameless.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * impl wi鑫充电服务
 *
 * @author 太阳偷渡青山
 * @description:
 * @create: 2023-02-25 15:00
 * @date 2023/03/10
 */
@Service
@Slf4j
public class WiXinRechargeServiceImpl implements WiXinRechargeService {

    @Autowired
    private WeiXiEntity weiXiEntity;

    @Value("${api_key}")
    private String api_key;
    /**
     * 根据订单号生成二维码地址
     *
     * @param clientId 客户机id
     * @param body     身体
     * @param totalFee 总费用
     * @param url      url
     * @return {@link Result}
     */
    @Override
    public Result<Map<String,Object>> createNative(Long clientId, String body, BigDecimal totalFee, String url) {
        // 自动生成单号
        String orderNum = UuidTradeNo.getOrderNum(clientId);
        weiXiEntity.setOut_trade_no(orderNum);

        // 自动生成随机码
        weiXiEntity.setNonce_str(WXPayUtil.generateNonceStr());
        // 真实价格  --- 这里写死 0分钱   weiXiEntity.setTotal_fee(totalFee.toString());
        weiXiEntity.setTotal_fee(new BigDecimal(0.01).multiply(new BigDecimal(100)).longValue()+"");
        // 商品描述
        weiXiEntity.setBody(body + ":" + totalFee + "元");
        // 支付成功后跳转的路径
        weiXiEntity.setNotify_url(url);
        // 将微信实体转为map集合
        Map mapWeixi = JSONObject.parseObject(JSON.toJSONString(weiXiEntity), Map.class);
            try {
                //2.远程调用微信支付接口
                HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                //设置支持https协议的请求
                httpClient.setHttps(true);
                //设置xml格式的参数
                httpClient.setXmlParam(WXPayUtil.generateSignedXml(mapWeixi, api_key));
                //发送请求
                httpClient.post();

                //获取返回的结果
                String content = httpClient.getContent();
                System.out.println(content);
                //把xml转化为map
                Map<String, String> map = WXPayUtil.xmlToMap(content);

                if(map.get("result_code").equals("SUCCESS")){
                    Map<String,Object> result=new HashMap<>();
                    result.put("codeUrl",map.get("code_url"));
                    result.put("price",totalFee);
                    result.put("title",weiXiEntity.getBody());
                    result.put("orderNo",weiXiEntity.getOut_trade_no());
                    return new Result<>(200,"获取二维码地址成功",result);
                }
            }catch (Exception e){
                 e.printStackTrace();
        }
        return new Result<>(500,"订单失效",null);

    }

    @Override
    public Result<String> queryPayStatus(String orderNo) {

         Map<String,String> params=new HashMap<>();
         params.put("appid",weiXiEntity.getAppid());
         params.put("mch_id",weiXiEntity.getMch_id());
         params.put("out_trade_no",orderNo);
        params.put("nonce_str", WXPayUtil.generateNonceStr());
        try {
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            httpClient.setHttps(true);
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(params, api_key));

            httpClient.post();
            String content = httpClient.getContent();

            Map<String, String> map = WXPayUtil.xmlToMap(content);
            if(map.get("trade_state").equals("SUCCESS")){
                return new Result<>(200,"支付成功",null);
            }else if (map.get("result_code").equals("FAIL")){
                return Result.error(map.get("err_code_des"));
            }

        }catch (Exception e){
            e.printStackTrace();
        }

        return new Result<>(500,"支付失败",null);
    }

    @Override
    public Result<Map<String, Object>> payExistingOrder(String orderNo, String body, BigDecimal totalFee, String url) {
        weiXiEntity.setOut_trade_no(orderNo);
        // 自动生成随机码
        weiXiEntity.setNonce_str(WXPayUtil.generateNonceStr());
        // 真实价格  --- 这里写死 0分钱   weiXiEntity.setTotal_fee(totalFee.toString());
        weiXiEntity.setTotal_fee(new BigDecimal(0.01).multiply(new BigDecimal(100)).longValue()+"");
        // 商品描述
        weiXiEntity.setBody(body + ":" + totalFee + "元");
        // 支付成功后跳转的路径
        weiXiEntity.setNotify_url(url);
        // 将微信实体转为map集合
        Map mapWeixi = JSONObject.parseObject(JSON.toJSONString(weiXiEntity), Map.class);
        String code_des = null;
        try {
            //2.远程调用微信支付接口
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置支持https协议的请求
            httpClient.setHttps(true);
            //设置xml格式的参数
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(mapWeixi, api_key));
            //发送请求
            httpClient.post();

            //获取返回的结果
            String content = httpClient.getContent();
            System.out.println(content);
            //把xml转化为map
            Map<String, String> map = WXPayUtil.xmlToMap(content);

            Map<String,Object> result=new HashMap<>();
            if(map.get("result_code").equals("SUCCESS")){
                result.put("codeUrl",map.get("code_url"));
                result.put("price",totalFee);
                result.put("title",weiXiEntity.getBody());
                result.put("orderNo",weiXiEntity.getOut_trade_no());
                return new Result<>(200,"获取二维码地址成功",result);
            }else {
                result.put("orderNo",weiXiEntity.getOut_trade_no());
                result.put("code_des",map.get("err_code_des"));
                return new Result<>(500,"订单失效",result);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return new Result<>(500,"订单失效",null);
    }
}
